package com.coder.security;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.coder.bean.WebResult;
import com.coder.util.ApiValidate;

public class AuthorInterceptor implements HandlerInterceptor{
	
	private Logger logger = LogManager.getLogger(AuthorInterceptor.class);
	
	static final String appsecret = "123456";
	
	static Map<String,String> map = new HashMap<String,String>();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		//判断参数是否输入正确
		String appId = request.getParameter("appid");
		if(StringUtils.isEmpty(appId)){
			returnJson(request,response,WebResult.getErrorResult(WebResult.Code.APPID_ERROR));
			return false;
		}
		String sign = request.getParameter("sign");
		if(StringUtils.isEmpty(sign)){
			returnJson(request,response,WebResult.getErrorResult(WebResult.Code.SIGN_ERROR));
			return false;
		}
		
		String timestamp = request.getParameter("timestamp");
		if(StringUtils.isEmpty(timestamp)){
			returnJson(request,response,WebResult.getErrorResult(WebResult.Code.TIMESTAMP_ERROR));
			return false;
		}
		
		//随机数
		String nonstr = request.getParameter("nonstr");
		if(StringUtils.isEmpty(nonstr)){
			returnJson(request,response,WebResult.getErrorResult(WebResult.Code.NONSTR_ERROR));
			return false;
		}
		
		String deviceId = request.getParameter("deviceId");
		if(StringUtils.isEmpty(nonstr)){
			returnJson(request,response,WebResult.getErrorResult(WebResult.Code.DEVICEID_ERROR));
			return false;
		}
		
		//判断请求是否唯一
		Long currentTimeMillis = System.currentTimeMillis();
		if(currentTimeMillis - Long.valueOf(timestamp) > 0 && currentTimeMillis - Long.valueOf(timestamp)<1000*60) {
			returnJson(request,response,WebResult.getErrorResult(WebResult.Code.REQUEST_ERROR));
			return false;
		}
		
		//校验签名是否正确
		WebResult result = ApiValidate.validateSign(request,sign,appsecret);
		if(!result.isSuccess()){
			returnJson(request,response,result);
			return false;
		}
		
		return true;
	}
	
	/**
	 * 返回JSON数据
	 * @param response
	 * @param json
	 * @throws Exception
	 */
	private void returnJson(HttpServletRequest request,HttpServletResponse response, WebResult<?> result) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result.toString());
        } catch (IOException e) {
            logger.error("response error",e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
